using Admin2025.Application.Services;
using Admin2025.Domain.Entities.App;
using Microsoft.AspNetCore.Mvc;

namespace Admin2025.Api.Controllers;

[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
    private readonly AuthService _authService;

    public AuthController(AuthService authService)
    {
        _authService = authService;
    }

    [HttpPost("register")]
    public async Task<IActionResult> Register([FromBody] RegisterRequest req)
    {
        try
        {
            var user = await _authService.RegisterAsync(req.Username, req.Password);
            return Ok(new { user.UserName });
        }
        catch (Exception ex)
        {
            return BadRequest(new { ex.Message });
        }
    }

    [HttpPost("login")]
    public async Task<IActionResult> Login([FromBody] LoginRequest req)
    {
        var user = await _authService.LoginAsync(req.Username, req.Password);
        if (user == null)
            return Unauthorized(new { message = "用户名或密码错误" });
        return Ok(new { user.UserName }); // 可返回Token等
    }

    public class RegisterRequest
    {
        public required string Username { get; set; }
        public required string Password { get; set; }
    }
    public class LoginRequest
    {
        public required string Username { get; set; }
        public required string Password { get; set; }
    }
}